from flask import Flask, render_template, request,session,redirect
from . import kaoshi
import json
from frameworks.utils.JsonResult2 import *
from frameworks.cores.LoadClass import *
import datetime

jsonResult = JsonResult2()
loader = LoadClass()

@kaoshi.route("/cat",methods=['GET', 'POST'])
def cat():
    name = request.args.get("pagename","cat")
    where = request.args.get("w","")
    print(where)
    dataurl = ""
    params = []
    if where != "":
        whereOption = where.split("|")
        for row in whereOption:
            option = row.split("@")
            params.append(option[0]+"("+option[1]+")")
        print(params)
        dataurl = "||".join(params)

    return render_template(
        'kaoshi/cat.html',
        dataurl="w="+dataurl,
        model=name
    )

@kaoshi.route("/question_cat",methods=['GET', 'POST'])
def question_cat():
    name = request.args.get("pagename","cat")
    where = request.args.get("w","")
    print(where)
    dataurl = ""
    params = []
    if where != "":
        whereOption = where.split("|")
        for row in whereOption:
            option = row.split("@")
            params.append(option[0]+"("+option[1]+")")
        print(params)
        dataurl = "||".join(params)

    return render_template(
        'kaoshi/question_cat.html',
        dataurl="w="+dataurl,
        model=name
    )


@kaoshi.route("/shijuan_detail",methods=['GET', 'POST'])
def shijuan_detail():
    name = request.args.get("pagename","cat")
    where = request.args.get("w","")
    print(where)
    dataurl = ""
    params = []
    if where != "":
        whereOption = where.split("|")
        for row in whereOption:
            option = row.split("@")
            params.append(option[0]+"("+option[1]+")")
        print(params)
        dataurl = "||".join(params)

    return render_template(
        'kaoshi/shijuan_detail.html',
        dataurl="w="+dataurl,
        model=name
    )

@kaoshi.route("/formadd",methods=['GET', 'POST'])
def formadd():
    model = request.args.get("model", "school")
    wherestr = request.args.get("w", "")
    fields = loader.load("controller.CommonController","CommonController",{
        "func":"getAddMap",
        "fields":["*"],
        "model": model
    })
    if wherestr.find(")") > 0 and wherestr.find("(") > 0:
        whereoption = wherestr.replace(")","").split("(")
        data = {whereoption[0]:whereoption[1]}
    else:
        data = []
    return render_template(
        'formadd.html',
        fields=fields,
        model=model,
        data=data
    )

@kaoshi.route("/question_formadd",methods=['GET', 'POST'])
def question_formadd():
    model = request.args.get("model", "school")
    wherestr = request.args.get("w", "")
    fields = loader.load("controller.CommonController","CommonController",{
        "func":"getAddMap",
        "fields":["*"],
        "model": model
    })
    if wherestr.find(")") > 0 and wherestr.find("(") > 0:
        whereoption = wherestr.replace(")","").split("(")
        data = {whereoption[0]:whereoption[1]}
    else:
        data = []
    return render_template(
        'kaoshi/question_formadd.html',
        fields=fields,
        model=model,
        data=data
    )

@kaoshi.route("/cat_shijuan",methods=['GET', 'POST'])
def cat_shijuan():
    name = request.args.get("pagename","cat")
    where = request.args.get("w","")
    print(where)
    dataurl = ""
    params = []
    if where != "":
        whereOption = where.split("|")
        for row in whereOption:
            option = row.split("@")
            params.append(option[0]+"("+option[1]+")")
        print(params)
        dataurl = "||".join(params)

    return render_template(
        'kaoshi/shijuan.html',
        dataurl="w="+dataurl,
        model=name
    )

@kaoshi.route("/cat_student_shijuan",methods=['GET', 'POST'])
def cat_student_shijuan():
    name = request.args.get("pagename","cat")
    where = request.args.get("w","")
    print(where)
    dataurl = ""
    params = []
    if where != "":
        whereOption = where.split("|")
        for row in whereOption:
            option = row.split("@")
            params.append(option[0]+"("+option[1]+")")
        print(params)
        dataurl = "||".join(params)

    return render_template(
        'kaoshi/student_kaoshi.html',
        dataurl="w="+dataurl,
        model=name
    )

@kaoshi.route("/cat_read",methods=['GET', 'POST'])
def cat_read():
    name = request.args.get("pagename","cat")
    where = request.args.get("w","")
    print(where)
    dataurl = ""
    params = []
    if where != "":
        whereOption = where.split("|")
        for row in whereOption:
            option = row.split("@")
            params.append(option[0]+"("+option[1]+")")
        print(params)
        dataurl = "||".join(params)

    return render_template(
        'cat_read.html',
        dataurl="w="+dataurl,
        model=name
    )

@kaoshi.route("/update",methods=['POST'])
def update():
    model = request.args.get("model", "school")
    response = request.get_data(as_text=True)
    data = json.loads(response)
    if "userid" in data:
        data["userid"] = session["userid"]
    rs = loader.load("controller.CommonController", "CommonController", {
        "func": "update",
        "data": data,
        "model": model
    })
    return jsonResult.setOk([], "更新成功")

@kaoshi.route("/add",methods=['POST'])
def add():
    model = request.args.get("model", "school")
    response = request.get_data(as_text=True)
    data = json.loads(response)
    if "userid" in data:
        data["userid"] = session["userid"]
    rs = loader.load("controller.CommonController", "CommonController", {
        "func": "add",
        "data": data,
        "model": model
    })
    return jsonResult.setOk([], "添加成功")

@kaoshi.route("/form",methods=['GET', 'POST'])
def form():
    model = request.args.get("model", "school")
    id = request.args.get("id", "0")
    fields = loader.load("controller.CommonController", "CommonController", {
        "func": "getEditMap",
        "fields": ["*"],
        "model": model
    })
    obj = loader.load("controller.CommonController","CommonController",{
        "func":"getRowData",
        "fields":["*"],
        "id": id,
        "model": model
    })
    print(obj)
    print(fields)
    return render_template(
        'kaoshi/form.html',
        obj=obj[0],
        fields=fields,
        model=model
    )

@kaoshi.route("/question_form",methods=['GET', 'POST'])
def question_form():
    model = request.args.get("model", "school")
    id = request.args.get("id", "0")
    fields = loader.load("controller.CommonController", "CommonController", {
        "func": "getEditMap",
        "fields": ["*"],
        "model": model
    })
    obj = loader.load("controller.CommonController","CommonController",{
        "func":"getRowData",
        "fields":["*"],
        "id": id,
        "model": model
    })
    print(obj)
    print(fields)
    return render_template(
        'kaoshi/question_form.html',
        obj=obj[0],
        fields=fields,
        model=model
    )

@kaoshi.route("/shijuan_form",methods=['GET', 'POST'])
def shijuan_form():
    model = request.args.get("model", "school")
    wherestr = request.args.get("w","")
    id = request.args.get("id", "0")
    fields = loader.load("controller.CommonController", "CommonController", {
        "func": "getEditMap",
        "fields": ["*"],
        "model": model
    })
    obj = loader.load("controller.CommonController", "CommonController", {
        "func": "getRowData",
        "fields": ["*"],
        "id": id,
        "model": model
    })
    questionData = loader.load("controller.CommonController", "CommonController", {
        "func": "getAllData",
        "data": "1",
        "model": "questions",
        "fields": "*"
    })
    print(questionData)
    if wherestr.find(")") > 0 and wherestr.find("(") > 0:
        whereoption = wherestr.replace(")","").split("(")
        data = {whereoption[0]:whereoption[1]}
    else:
        data = []
    return render_template(
        'kaoshi/shijuan_form.html',
        obj=obj[0],
        fields=fields,
        model=model,
        data=data,
        questionData=questionData
    )

@kaoshi.route("/shijuan_add",methods=['GET', 'POST'])
def shijuan_add():
    model = request.args.get("model", "school")
    wherestr = request.args.get("w", "")
    fields = loader.load("controller.CommonController", "CommonController", {
        "func": "getAddMap",
        "fields": ["*"],
        "model": model
    })
    # 获取git仓库信息
    questionData = loader.load("controller.CommonController", "CommonController", {
        "func": "getAllData",
        "data": "1",
        "model": "questions",
        "fields": "*"
    })
    print(questionData)
    whereoption = wherestr.replace(")", "").split("(")
    data = {whereoption[0]: whereoption[1]}
    return render_template(
        'kaoshi/shijuan_add.html',
        fields=fields,
        model=model,
        data=data,
        questionData=questionData
    )

@kaoshi.route("/cols",methods=['GET','POST'])
def cols():
    model = request.args.get("model", "school")
    width = request.args.get("width", "200")
    rs = loader.load("controller.CommonController", "CommonController", {
        "func":"getColumns",
        "fields":["*"],
        "model":model,
        "width":width
    })
    return jsonResult.setOk(rs,"获取成功")

@kaoshi.route("/listdata",methods=['GET'])
def listdata():
    model = request.args.get("model", "school")
    wherestr = request.args.get("w", "")
    num = request.args.get("limit",10)
    page = request.args.get("page",1)
    if wherestr != "":
        wherestr = wherestr.replace("(", "='").replace(")", "'").replace("||", " and ")
    else:
        wherestr = "1"
    if model in ["account_detail","account_exchange","stock_holds_detail","stock_select"]:
        wherestr += " and userid="+str(session["userid"])
    if session["role"] == "student" and model in["exam_record"]:
        wherestr += " and uid="+str(session["userid"])
    data = loader.load("controller.CommonController", "CommonController", {
        "func": "getData",
        "fields": ["*"],
        "page": page,
        "num": num,
        "orderfield": "id",
        "asc": "asc",
        "model": model,
        "where": wherestr
    })
    return json.dumps(data)

@kaoshi.route("/question_submit",methods=['POST'])
def question_submit():
    param = {}
    for key in request.form.keys():
        param[key] = request.form.getlist(key)
    data = loader.load("controller.ExamPaperController", "ExamPaperController", {
        "func": "addUserExamPaper",
        "params": param,
        "userid": session["userid"],
        "endtime": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    })
    return jsonResult.setOk({"score":data},"获取成功")

@kaoshi.route("/must_question_submit",methods=['POST'])
def must_question_submit():
    param = {}
    for key in request.form.keys():
        param[key] = request.form.getlist(key)
    data = loader.load("controller.ExamPaperController", "ExamPaperController", {
        "func": "addUserMustExamPaper",
        "params": param,
        "userid": session["userid"],
        "endtime": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    })
    return "hello"